package com.znz.analysis.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.znz.analysis.bean.Location;
import com.znz.analysis.constant.enumeration.HttpMethod;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author 作者 :TP
 * @version 创建时间：2017年6月22日 上午1:06:07
 *
 */
public class GeoLite2Util {
	private static Logger logger = Logger.getLogger(GeoLite2Util.class.getName());

	// public static Location getLocationByIp(String ip) throws Exception {
	// Location location = new Location();
	// DatabaseReader reader =
	// GeoLite2DataBaseReader.getInstance().getDatabaseReader();
	// InetAddress ipAddress = InetAddress.getByName(ip);
	// try {
	// CityResponse response = reader.city(ipAddress);
	//
	// // country
	// Country country = response.getCountry();
	// String country_str = country.getNames().get("zh-CN");
	// if (country_str != null) {
	// // 对港澳台的特殊处理
	// if (country_str.contains("香港") || country_str.contains("台湾") ||
	// country_str.contains("澳门") ) {
	// location.setCountry("中国");
	// location.setProvince(country_str);
	// location.setCity("");
	// } else {
	// location.setCountry(country_str);
	// // province
	// Subdivision subdivision = response.getMostSpecificSubdivision();
	// location.setProvince(subdivision.getNames().get("zh-CN"));
	// // city
	// City city = response.getCity();
	// location.setCity(city.getNames().get("zh-CN"));
	// }
	// }
	// } catch (AddressNotFoundException e) {
	// // logger.warn(e.getMessage(), e);
	// }
	// return location;
	// }

	@SuppressWarnings("unchecked")
	public static Location getLocationByIp(String url, String ip) throws Exception {
		Location location = new Location();
		HttpRequest request = new HttpRequest();
		JSONObject query_ip = new JSONObject();
		JSONObject paramJson = new JSONObject();
		query_ip.put("query_ip", ip);
		paramJson.element("query_ip", query_ip);
		String response = request.sendJson(url, paramJson, HttpMethod.POST);
		if (StringUtils.isNotBlank(response)) {
			JSONObject responseObject = JSONObject.fromObject(response);
			if (responseObject.containsKey("code") && responseObject.getInt("code") == 1000) {
				JSONArray data = responseObject.getJSONArray("data");
				if (data.size() > 0) {
					location.setCountry(((JSONObject) data.get(0)).getJSONObject("location2json").getString("country"));
					location.setProvince(
							((JSONObject) data.get(0)).getJSONObject("location2json").getString("province"));
					location.setCity(((JSONObject) data.get(0)).getJSONObject("location2json").getString("city"));
				}
			}
		}
		System.out.println(location + " " + ip);
		return location;
	}

	public static void main(String[] args) {
		// String[] arr = { "59.61.240.255" };
		// List<String> list = Arrays.asList(arr);
		// list.forEach(i -> {
		// while (true) {
		// try {
		// System.out.println(getLocationByIp(i.toString()));
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		// });
	}
}
